<template>
  <div class="pages customer">
    <div class="container_box">
      <div class="tableSearch">
        <el-button v-if="permission==1" type="primary" @click="submitForm('ruleForm')" size="mini">保存</el-button>
        <el-button v-if="permission==0 && setRole('修改')" type="primary" @click="editstatus()" size="mini">修改</el-button>
      </div>

      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" :inline="true" label-width="140px" class="system" size="small">
        <el-row>
          <el-form-item class="" label="启用">
            <el-checkbox :disabled="permission==0" v-model="ruleForm.status"></el-checkbox>
          </el-form-item>
        </el-row>
        <el-row class="rowspace" :gutter="40">
          <el-col :span="8">
            <el-form-item class="" label="供应商名称:" prop="name">
              <el-input @keyup.native='replace(ruleForm.name, ruleForm, "name")' v-if="permission == 1 && ruleForm.auditState != 1 && ruleForm.auditState != 3" maxlength="16" v-model="ruleForm.name"></el-input>
              <span v-else>{{ruleForm.name}}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item class="" label="供应商地址:" prop="address">
              <el-input v-if="permission == 1 && ruleForm.auditState != 1 && ruleForm.auditState != 3" maxlength="16" v-model="ruleForm.address"></el-input>
              <span v-else>{{ruleForm.address}}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item class="" label="法人:" prop="principal">
              <el-input @keyup.native='replace(ruleForm.principal, ruleForm, "principal")' v-if="permission == 1 && ruleForm.auditState != 1 && ruleForm.auditState != 3" maxlength="18" v-model="ruleForm.principal"></el-input>
              <span v-else>{{ruleForm.principal}}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="rowspace" :gutter="40">
          <el-col :span="8">
            <el-form-item class="" label="统一社会信用代码:" prop="creditCode">
              <el-input @keyup.native='replace(ruleForm.creditCode,ruleForm,"creditCode")' v-if="permission == 1 && ruleForm.auditState != 1 && ruleForm.auditState != 3 && ruleForm.auditState != 4 && ruleForm.auditState != 5" maxlength="18" v-model="ruleForm.creditCode"></el-input>
              <span v-else>{{ruleForm.creditCode}}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item class="" label="法人手机号:" prop="linkPhone">
              <el-input @keyup.native='replace(ruleForm.linkPhone,ruleForm,"linkPhone")' v-if="permission == 1 && ruleForm.auditState != 1 && ruleForm.auditState != 3 && ruleForm.auditState != 4 && ruleForm.auditState != 5" maxlength="11" v-model="ruleForm.linkPhone"></el-input>
              <span v-else>{{ruleForm.linkPhone}}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="邮箱:" prop="email">
              <el-input @keyup.native='replace(ruleForm.email,ruleForm,"email")' v-if="permission == 1 && ruleForm.auditState != 1 && ruleForm.auditState != 3" maxlength="30" v-model="ruleForm.email"></el-input>
              <span v-else>{{ruleForm.email}}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="rowspace" :gutter="40">
          <el-col :span="8">
            <el-form-item label="法人身份证号码:" prop="idcardNumber">
              <el-input oninput="value=value.replace(/[^\d|xX]/g,'')" onafterpaste="value=value.replace(/[^\d|xX]/g,'')" maxlength="18" v-if="permission == 1 && ruleForm.auditState != 1 && ruleForm.auditState != 3" v-model="ruleForm.idcardNumber"></el-input>
              <span v-else>{{ruleForm.idcardNumber}}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="食品流通许可证号:" prop="foodLicenseNumber">
              <el-input @keyup.native='replace(ruleForm.foodLicenseNumber,ruleForm,"foodLicenseNumber")' v-if="permission == 1 && ruleForm.auditState != 1 && ruleForm.auditState != 3" v-model="ruleForm.foodLicenseNumber"></el-input>
              <span v-else>{{ruleForm.foodLicenseNumber}}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item class="" label="注册资金（万元）:" prop="registeredCapital">
              <el-input onkeyup="this.value= this.value.match(/\d+(\.\d{0,2})?/) ? this.value.match(/\d+(\.\d{0,2})?/)[0] : ''" onafterpaste="this.value= this.value.match(/\d+(\.\d{0,2})?/) ? this.value.match(/\d+(\.\d{0,2})?/)[0] : ''" v-if="permission == 1 && ruleForm.auditState != 1 && ruleForm.auditState != 3" maxlength="16" v-model="ruleForm.registeredCapital"></el-input>
              <span v-else>{{ruleForm.registeredCapital}}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="rowspace" :gutter="40">
          <el-col :span="8">
            <el-form-item class="" label="固定电话:" prop="fixPhone">
              <el-input v-if="permission == 1 && ruleForm.auditState != 1 && ruleForm.auditState != 3" maxlength="12" v-model="ruleForm.fixPhone"></el-input>
              <span v-else>{{ruleForm.fixPhone}}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item class="" label="传真:" prop="fax">
              <el-input oninput="this.value=this.value.replace(/\D/g,'')" onafterpaste="this.value=this.value.replace(/\D/g,'')" v-if="permission == 1 && ruleForm.auditState != 1 && ruleForm.auditState != 3" maxlength="16" v-model="ruleForm.fax"></el-input>
              <span v-else>{{ruleForm.fax}}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item class="" label="备注:" prop="remark">
              <el-input v-if="permission == 1 && ruleForm.auditState != 1 && ruleForm.auditState != 3" type="textarea" :rows="2" v-model="ruleForm.remark"></el-input>
              <span v-else>{{ruleForm.remark}}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="40">
          <el-col :span="8">
            <el-form-item label="供应商类型">
              <el-checkbox-group v-model="serviceTypeNumList" size="mini" :disabled="permission != 1">
                <el-checkbox v-for='item in serviceTypeList' :label="item.serviceProviderTypeNumber" :key='item.serviceProviderTypeNumber'>{{item.serviceProviderTypeName}}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item class="" :label="serviceTypeList[0].serviceProviderTypeName" size='small'>
              <el-select :disabled="permission != 1" v-model="ruleForm.serviceInfoId" placeholder="请选择" style='width: 100%' @change='selectChange'>
                <el-option label='请选择' value=''></el-option>
                <el-option v-for='item in serviceList' :key='item.serviceInfoId' :label="item.serviceName" :value="item.serviceInfoId"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="7">
            <el-form-item class="rowtwo" label="商户LOGO" prop="logoUrl">
              <div class="imgbox"><img :src="ruleForm.logoUrl" @click="showimg(ruleForm.logoUrl)" alt=""></div>
              <el-upload v-if="ruleForm.auditState != 1 && ruleForm.auditState != 3" class="upload-demo" action="1" :show-file-list="false" :before-upload="beforeAvatarUpload" :http-request="uploadSectionFile">
                <el-button :disabled="permission==0" @click="addindex('logoUrl')" type="primary">点击上传</el-button>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item class="rowtwo" label="营业执照信息" prop="licenseUrl">
              <div class="imgbox"><img :src="ruleForm.licenseUrl" @click="showimg(ruleForm.licenseUrl)" alt=""></div>
              <el-upload v-if="ruleForm.auditState != 1 && ruleForm.auditState != 3" class="upload-demo" action="1" :show-file-list="false" :before-upload="beforeAvatarUpload" :http-request="uploadSectionFile">
                <el-button :disabled="permission==0" @click="addindex('licenseUrl')" type="primary">点击上传</el-button>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item class="rowtwo" label="食品流通许可证" prop="foodUrl">
              <div class="imgbox"><img :src="ruleForm.foodUrl" @click="showimg(ruleForm.foodUrl)" alt=""></div>
              <el-upload v-if="ruleForm.auditState != 1 && ruleForm.auditState != 3" class="upload-demo" action="1" :show-file-list="false" :before-upload="beforeAvatarUpload" :http-request="uploadSectionFile">
                <el-button :disabled="permission==0" @click="addindex('foodUrl')" type="primary">点击上传</el-button>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="40">
          <el-col :span="7">
            <el-form-item class="rowtwo" label="法人身份证正面" prop="idcardFront">
              <div class="imgbox"><img :src="ruleForm.idcardFront" @click="showimg(ruleForm.idcardFront)" alt=""></div>
              <el-upload v-if="ruleForm.auditState != 1 && ruleForm.auditState != 3" class="upload-demo" action="1" :show-file-list="false" :before-upload="beforeAvatarUpload" :http-request="uploadSectionFile">
                <el-button :disabled="permission==0" @click="addindex('idcardFront')" type="primary">点击上传</el-button>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item class="rowtwo" label="法人身份证反面" prop="idcardReverse">
              <div class="imgbox"><img :src="ruleForm.idcardReverse" @click="showimg(ruleForm.idcardReverse)" alt=""></div>
              <el-upload v-if="ruleForm.auditState != 1 && ruleForm.auditState != 3" class="upload-demo" action="1" :show-file-list="false" :before-upload="beforeAvatarUpload" :http-request="uploadSectionFile">
                <el-button :disabled="permission==0" @click="addindex('idcardReverse')" type="primary">点击上传</el-button>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
  </div>
</template>
<script>
import u from "@/util";
import { mapState } from "vuex";
import {
  selectBaseShop,
  insertBaseShop,
  uploadFile,
  updateBaseShop,
  getFile,
  findServiceProviderByTypeNumberList
} from "@/api";
import { isFunction } from "util";
export default {
  computed: mapState(["power", "merchantId"]),
  data() {
    const validSocialCreditCode = (rule, value, callback) => {
      if (value && !u.validSocialCreditCode(value)) {
        return callback(new Error("格式不正确（18位数字或者大写英文字母）！"));
      } else {
        callback();
      }
    };
    const validTelPhone = (rule, value, callback) => {
      if (value && !u.validTelPhone(value)) {
        return callback(new Error("固定电话格式不正确 "));
      } else {
        callback();
      }
    };
    const validEmail = (rule, value, callback) => {
      if (!u.validEmail(value)) {
        return callback(new Error("邮件格式不正确！"));
      } else {
        callback();
      }
    };
    return {
      radio1: "",
      permission: 0, //0:查看,1修改
      labelPosition: "top",
      imgIndex: "", //当前上传
      showErrMsg: false,
      areaIndex: "", // 正在修改的供应商地址
      ruleForm: {
        status: true, //启用
        name: "", //门店名称
        address: "", //门店地址
        principal: "", //法人
        creditCode: "", //社会统一信用代码
        registeredCapital: "", //注册资金
        taxesType: "", //纳税人类型
        linkName: "", //联系人
        linkPhone: "", //联系电话
        fixPhone: "", //固定电话
        registeredCapital: "", //注册资金
        fax: "", //传真
        email: "", //邮箱
        remark: "", //备注
        logoUrl: "", //logoUrl
        licenseUrl: "", //营业执照
        foodUrl: "", //食品流通许可证
        idcardFront: "", //身份证正面
        idcardReverse: "", //身份证反面
        idcardReverse: "",
        serviceInfoId: "", //服务商信息Id
        serviceProviderTypeNumber: "T02" //服务商类型编号
      },
      rules: {
        name: [
          { required: true, message: "请输入供应商名称", trigger: "blur" },
          { validator: u.checkSpace, trigger: "blur" }
        ],
        address: [
          { required: true, message: "请输入供应商地址", trigger: "blur" },
          { validator: u.checkSpace, trigger: "blur" }
        ],
        principal: [
          { required: true, message: "请输入法人", trigger: "blur" },
          { validator: u.checkSpace, trigger: "blur" }
        ],
        creditCode: [
          {
            required: true,
            message: "请输入统一社会信用代码",
            trigger: "blur"
          },
          { validator: validSocialCreditCode, trigger: "blur" }
        ],
        linkPhone: [
          { required: true, message: "请输入手机号" },
          {
            validator: u.validatePhone,
            trigger: "blur",
            message: "请输入手机号"
          }
        ],
        fixPhone: [{ validator: validTelPhone, trigger: "blur" }],
        licenseUrl: [{ required: true, message: "公司营业执照信息（副本)" }],
        idcardFront: [{ required: true, message: "法人身份证正面电子版" }],
        idcardReverse: [{ required: true, message: "法人身份证反面电子版" }],
        email: [
          { required: true, message: "请填写邮箱" },
          { validator: validEmail, trigger: "blur" }
        ]
      },
      serviceTypeList: [
        {
          serviceProviderTypeName: "商品服务商",
          serviceProviderTypeNumber: "T02"
        }
      ],
      serviceTypeNumList: ["T02"],
      serviceList: []
    };
  },
  mounted() {
    this.getServiceList();
    this.permission = u.getQuery("status");
    this.id = u.getQuery("id");
    if (this.permission == 1) {
      this.permission = 1;
    } else {
      this.permission = 0;
      this.id = u.getQuery("id");
      this.getdeteils(this.id);
    }
  },
  methods: {
    replace(value, obj, key) {
      let that = this;
      let event = event || window.event;
      if (event.keyCode == 13) {
        setTimeout(() => {
          that.validItem(value, obj, key);
        }, 100);
      } else {
        that.validItem(value, obj, key);
      }
    },
    // 输入框验证
    validItem(value, obj, key) {
      let res = "";
      switch (key) {
        case "name":
          res = u.replaceChineseAndBracket(value);
          break;
        case "linkName":
        case "principal":
          res = u.replaceChineseAndLetter(value);
          break;
        case "linkPhone":
        case "phone":
        case "mobile":
          res = u.replaceNumber(value);
          break;
        case "landline":
        case "fixPhone":
          res = u.replaceFixPhone(value);
          break;
        case "email":
          res = u.replaceEmail(value);
          break;
        case "creditCode":
        case "idcardNumber":
        case "foodLicenseNumber":
          res = u.replaceSocialCreditCode(value);
          break;
        case "registeredCapital":
          res = u.twoDecimal(value);
          break;
        case "fax":
          res = u.moreThanZero(value);
          break;
      }
      this.$set(obj, key, res);
    },
    getServiceList() {
      let data = {
        shopId: this.merchantId,
        serviceProviderTypeNumber: this.serviceTypeNumList[0]
      };
      findServiceProviderByTypeNumberList(data).then(res => {
        if (res.code == 200) {
          this.serviceList = res.data.list;
        }
      });
    },
    selectChange(val) {},
    //配置权限
    setRole(key) {
      return u.selectTitle(this.power, key);
    },
    // 图片大小格式
    beforeAvatarUpload(file) {
      const isJPG =
        file.type === "image/png" ||
        file.type === "image/jpg" ||
        file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传图片格式错误!");
      }
      if (!isLt2M) {
        this.$message.error("只能上传jpg/png文件，且不超过2M!");
      }
      return isJPG && isLt2M;
    },
    // 上传
    uploadSectionFile(param) {
      var fileObj = param.file;
      var data = new FormData();
      data.append("projectName", fileObj.name);
      data.append("file", fileObj);
      uploadFile(data).then(res => {
        if (res.code == 200) {
          let a = `${getFile}?id=${res.data.id}`;
          switch (this.imgIndex) {
            case "logoUrl":
              this.ruleForm.logoUrl = a;
              break;
            case "licenseUrl":
              this.ruleForm.licenseUrl = a;
              break;
            case "foodUrl":
              this.ruleForm.foodUrl = a;
              break;
            case "idcardFront":
              this.ruleForm.idcardFront = a;
              break;
            case "idcardReverse":
              this.ruleForm.idcardReverse = a;
              break;
            default:
              break;
          }
        } else {
          this.$message.error("图片上传失败");
        }
      });
    },
    // 区别上传图片
    addindex(i) {
      this.imgIndex = i;
    },
    // 打开大图
    showimg(url) {
      window.open(url);
    },
    // 新建修改
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let postdata = this.ruleForm;
          postdata.businessId = this.merchantId;
          postdata.type = 1;
          postdata.isStore = 1;
          postdata.isTenant = 1;
          postdata.source = 3; //2：商户平台门店管理；3：商户平台供应商管理；4：商户平台客户管理'
          if (postdata.status == true) {
            postdata.status = 0;
          } else {
            postdata.status = 1;
          }
          if (this.id != "") {
            this.ruleForm.id = this.id;
            updateBaseShop(postdata)
              .then(res => {
                if (res.code == 200) {
                  this.$message.success(res.msg);
                  u.routerTo(
                    "/operate-management/supplier-management/supplier-supplierMg"
                  );
                } else {
                  this.$message.error(res.msg);
                }
              })
              .catch(err => {});
          } else {
            insertBaseShop(postdata)
              .then(res => {
                if (res.code == 200) {
                  this.$message.success(res.msg);
                  u.routerTo(
                    "/operate-management/supplier-management/supplier-supplierMg"
                  );
                }
              })
              .catch(err => {
                this.loading = false;
              });
          }
        } else {
          this.$message.error("请检查必填信息");
          return false;
        }
      });
    },
    // 查看详情
    getdeteils(id) {
      let data = {
        id: id,
        businessId: this.merchantId,
        type: 1
      };
      selectBaseShop(data).then(res => {
        if (res.code == 200) {
          if (res.data.status == 0) {
            res.data.status = true;
          } else {
            res.data.status = false;
          }
          this.ruleForm = res.data;
          this.ruleForm.oldLinkPhone = this.ruleForm.linkPhone; // //商户旧手机号
          this.ruleForm.serviceProviderTypeNumber = "T02";
        }
      });
    },
    // 点击修改
    editstatus() {
      this.permission = 1;
    }
  }
};
</script>

<style scoped>
.container_box {
  padding: 0px 20px;
}
.el-tab-pane .el-row {
  width: 95%;
}
.imgbox {
  width: 180px;
  height: 150px;
  border: 1px dashed #dcdfe6;
}
.imgbox img {
  width: 100%;
  height: 100%;
}
.contact-content {
  width: 100%;
  height: auto;
  margin: 10px auto;
  padding: 10px 0;
  border-top: solid 1px #999;
}
.contact-content .el-select {
  width: 120px;
}
.contact-content .supp-name .el-input {
  width: 150px;
}
.span-item {
  margin-right: 30px;
}
</style>
